package jsu.bza.work2;

import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/w2")
public class UserController {
private List<User> users=new ArrayList<>();
public UserController() {
    users.add(new User(1L,"u1","2345678901@qq.com","123", LocalDateTime.now(),"ACTIVE"));
    users.add(new User(2L,"u2","1234567898@qq.com","456", LocalDateTime.now().minusDays(6),"ACTIVE"));
    users.add(new User(3L,"u3","143543254@qq.com","789", LocalDateTime.now().minusDays(100),"ACTIVE"));
    users.add(new User(4L,"u4","1232123432@qq.com","321",LocalDateTime.now(),"ACTIVE"));
}
@GetMapping("/users")//获取所有用户
    public ApiResponse<List<User>> getAll(){
    return ApiResponse.success("获取所有用户成功",users);
}
@PostMapping("/users")//新增用户
    public ApiResponse<User> addUser(@RequestBody User user) {
    System.out.println(user);
    user.setId((long)(users.size()+1));
    user.setRegistrationDate(LocalDateTime.now());
    users.add(user);
    return ApiResponse.success("新增用户成功",user);
}
@GetMapping("/users/{id}")//获取单个用户
    public ApiResponse<User> getById(@PathVariable("id") long id){
    User user=users.stream().filter(u->u.getId().equals(id)).findFirst().orElse(null);
    if(user==null){
        return ApiResponse.error("用户未找到，ID：" + id,"USER_NOT_FOUND");
    }
    return ApiResponse.success("查询用户成功", user);
}
@PutMapping("/users/{id}")//更新用户
    public ApiResponse<User> updateUser(@PathVariable("id") long id,@RequestBody User updateUser){
    User existingUser=users.stream().filter(u->u.getId().equals(id)).findFirst().orElse(null);
    if(existingUser==null){
        return ApiResponse.error("用户未找到，ID：" + id,"USER_NOT_FOUND");
    }
    existingUser.setName(updateUser.getName());
    existingUser.setEmail(updateUser.getEmail());
    existingUser.setPassword(updateUser.getPassword());
    existingUser.setRegistrationDate(LocalDateTime.now());
    existingUser.setStatus(updateUser.getStatus());
    return ApiResponse.success("更新成功", existingUser);
}
@DeleteMapping("/users/{id}")
    public ApiResponse deleteUser(@PathVariable("id") long id){
    User  user=users.stream().filter(u->u.getId().equals(id)).findFirst().orElse(null);
    if(user==null){
        return ApiResponse.error("用户未找到，ID：" + id,"USER_NOT_FOUND");
    }
    users.remove(user);
    return ApiResponse.success("用户ID：" + id +" 已删除",null);
}
}
